package com.cn.lp.export.server.base;

import com.cn.lp.export.server.base.context.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;

/**
 * 全局异常拦截
 */
@ControllerAdvice
public class WebExceptionHandler {

    private static final Logger LOG = LoggerFactory.getLogger(WebExceptionHandler.class);

    /**
     * 参数校验统一异常处理
     */
    @ExceptionHandler(ExportException.class)
    @ResponseBody
    public CommandResult handleBindException(ExportException ex) {
        return ResponseResultFactory.fail(ex.getCode(), ex.getMessage());
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public CommandResult sqlException(HttpServletRequest req, Exception sqlEx) {
        logException(req, sqlEx, false);
        return ResponseResultFactory.fail(CoreResponseCode.UNKNOWN_ERROR.getCode(), "执行异常，请稍后再试");
    }

    private void logException(HttpServletRequest req, Exception e, boolean printlnTrace) {
        if (LOG.isWarnEnabled()) {
            LOG.warn("请求异常：[uri={},method={},e={}]", req.getRequestURI(), req.getMethod(), e.getClass());
            LOG.warn(e.getMessage());
            if (printlnTrace) {
                LOG.warn("StackTrace: {}", e);
            }
        }
    }

}
